package de.tud.etit.blipz;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import de.tud.etit.blipz.entities.User;
import de.tud.etit.blipz.exceptions.ApplicationException;
import de.tud.etit.blipz.services.json.UserService;
import de.tud.etit.blipz.services.storage.GlobalStorage;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {

	private final static String CREDENTIAL_FILENAME = "de.tud.etit.CRETENIALFILENAME.txt";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mobileNr;
	private String password;
	private boolean autologin;

	// UI references.
	private EditText mobileNrView;
	private EditText passwordView;
	private CheckBox autologinView;
	private View loginFormView;
	private View loginStatusView;
	private TextView loginStatusMessageView;

	private Activity currentActivity;
	private UserService userService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		GlobalStorage.setCredentialFile(new File(getApplicationContext()
//				.getFilesDir(), CREDENTIAL_FILENAME));
		GlobalStorage.setContext(getApplicationContext());
		GlobalStorage.setCredentialFileName(CREDENTIAL_FILENAME);
		setContentView(R.layout.activity_login);
		currentActivity = this;
		userService = new UserService();
		mobileNrView = (EditText) findViewById(R.id.mobileNr);
		passwordView = (EditText) findViewById(R.id.password);
		passwordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							setCredentials();
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		autologinView = (CheckBox) findViewById(R.id.autologin);

		loginFormView = findViewById(R.id.login_form);
		loginFormView.setVisibility(View.INVISIBLE);
		loginStatusView = findViewById(R.id.login_status);
		loginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		setViewVisibility(View.INVISIBLE);
		autoLogin();

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						setCredentials();
						attemptLogin();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
	}

	public void autoLogin() {
		if (GlobalStorage.getUser() == null || GlobalStorage.getUser().isAutoLogin() == null
				|| GlobalStorage.getUser().isAutoLogin() == false) {
			setViewVisibility(View.VISIBLE);
			return;
		}

		mobileNr = GlobalStorage.getUser().getMobileNr();
		password = GlobalStorage.getUser().getPassword();
		autologin = GlobalStorage.getUser().isAutoLogin();

		attemptLogin();

	}

	public void setViewVisibility(int visibility) {
		mobileNrView.setVisibility(visibility);
		passwordView.setVisibility(visibility);
		autologinView.setVisibility(visibility);
		loginFormView.setVisibility(visibility);
		findViewById(R.id.sign_in_button).setVisibility(visibility);
	}

	public void setCredentials() {
		mobileNr = mobileNrView.getText().toString();
		password = passwordView.getText().toString();
		autologin = autologinView.isChecked();
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		mobileNrView.setError(null);
		passwordView.setError(null);

		boolean cancel = false;
		View focusView = null;

		if (TextUtils.isEmpty(password)) {
			passwordView.setError(getString(R.string.error_field_required));
			focusView = passwordView;
			cancel = true;
		} else if (password.length() < 4) {
			passwordView.setError(getString(R.string.error_invalid_password));
			focusView = passwordView;
			cancel = true;
		}

		if (TextUtils.isEmpty(mobileNr)) {
			mobileNrView.setError(getString(R.string.error_field_required));
			focusView = mobileNrView;
			cancel = true;
		} else if (mobileNr.length() < 6) {
			mobileNrView.setError(getString(R.string.error_invalid_mobileNr));
			focusView = mobileNrView;
			cancel = true;
		}

		if (cancel) {
			focusView.requestFocus();
		} else {
			loginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			loginStatusView.setVisibility(View.VISIBLE);
			loginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							loginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			loginFormView.setVisibility(View.VISIBLE);
			loginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							loginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			loginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			loginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	public boolean createNewUser() {
		User user = null;

		if (mobileNr != null && mobileNr.isEmpty() == false && password != null
				&& password.isEmpty() == false) {
			user = new User();
			user.setMobileNr(mobileNr);
			user.setPassword(password);
			user.setAutoLogin(autologin);

			GlobalStorage.setUser(user);
		}

		try {
			this.userService.register(GlobalStorage.getUser());

			return true;
		} catch (ApplicationException ex) {
			return false;
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {

			return createNewUser();
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				finish();
				Intent intent = new Intent(currentActivity, MapActivity.class);

				startActivity(intent);
			} else {
				setViewVisibility(View.VISIBLE);
				passwordView
						.setError(getString(R.string.error_incorrect_password));
				passwordView.requestFocus();
				DialogFragment dialog = new RegistrationFailedDialog();
				dialog.show(getFragmentManager(), "registrationFailed");
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
}
